package com.lagou.web;

import com.lagou.domain.User;
import com.lagou.service.LoginService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1. 设定对请求解析的编码格式和响应的解析格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        // 2. 读取参数username和password的内容
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 3. 创建User对象
        User user = new User(username, password);
        // 4. 创建LoginService对象，调用isUser方法判断是否为用户
        LoginService service = new LoginService();

        boolean isUser = false;
        try {
            isUser = service.isUser(user);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        // 用户验证后，有此用户
        if (isUser) {
            HttpSession session = req.getSession();
            session.setAttribute("user", username);
            resp.sendRedirect("/student_management_system/add_student.html");
        } else {
            req.setAttribute("msg", "账号或密码输入有误，请核对后重新输入");
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/index.jsp");
            requestDispatcher.forward(req, resp);
        }
/*        String pr = isUser ? "登录成功" : "账号或密码输入有误，请核对后重新输入";
        resp.getWriter().print(pr);*/
    }
}
